package com.car.service.controller;

import com.car.service.dto.request.MessageRequest;
import com.car.service.dto.request.PageRequest;
import com.car.service.dto.response.PageResponse;
import com.car.service.dto.response.Result;
import com.car.service.entity.ChatMessage;
import com.car.service.service.ChatMessageService;
import com.car.service.vo.ChatMessageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 聊天消息控制器
 */
@RestController
@RequestMapping("/api/chat/message")
public class ChatMessageController {
    
    @Autowired
    private ChatMessageService chatMessageService;
    
    /**
     * 发送消息
     */
    @PostMapping
    public Result<ChatMessageVO> sendMessage(@Valid @RequestBody MessageRequest request,
                                          @RequestHeader("X-User-Id") Long userId,
                                          @RequestHeader("X-User-Type") Integer userType) {
        ChatMessage message = new ChatMessage();
        message.setSessionId(request.getSessionId());
        message.setSenderId(userId);
        message.setSenderType(userType);
        message.setReceiverId(request.getReceiverId());
        message.setContent(request.getContent());
        message.setMessageType(request.getMessageType());
        
        ChatMessage savedMessage = chatMessageService.saveMessage(message);
        return Result.success(ChatMessageVO.fromEntity(savedMessage));
    }
    
    /**
     * 获取会话消息列表
     */
    @GetMapping("/session/{sessionId}")
    public Result<PageResponse<ChatMessageVO>> getSessionMessages(
            @PathVariable String sessionId,
            @ModelAttribute PageRequest pageRequest) {
        List<ChatMessage> messages = chatMessageService.getMessagesBySessionId(
                sessionId, pageRequest.getPage(), pageRequest.getSize());
        
        List<ChatMessageVO> voList = messages.stream()
                .map(ChatMessageVO::fromEntity)
                .collect(Collectors.toList());
        
        // 这里简化处理，实际应该查询总数
        long total = voList.size();
        
        return Result.success(
                PageResponse.of(voList, total, pageRequest.getPage(), pageRequest.getSize()));
    }
    
    /**
     * 标记消息已读
     */
    @PutMapping("/session/{sessionId}/read")
    public Result<Void> markMessagesAsRead(
            @PathVariable String sessionId,
            @RequestHeader("X-User-Id") Long userId) {
        chatMessageService.markMessagesAsRead(sessionId, userId);
        return Result.success();
    }
    
    /**
     * 获取未读消息数
     */
    @GetMapping("/session/{sessionId}/unread")
    public Result<Integer> getUnreadMessageCount(
            @PathVariable String sessionId,
            @RequestHeader("X-User-Id") Long userId) {
        int count = chatMessageService.getUnreadMessageCount(sessionId, userId);
        return Result.success(count);
    }
    
    /**
     * 删除消息
     */
    @DeleteMapping("/{messageId}")
    public Result<Void> deleteMessage(@PathVariable Long messageId) {
        chatMessageService.deleteMessage(messageId);
        return Result.success();
    }
} 